package com.yangle.frame.admin.security;


import com.alibaba.fastjson.JSON;
import com.baidu.aip.face.AipFace;
import com.yangle.frame.admin.entity.JsonRootBean;
import com.yangle.frame.admin.entity.Result;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;

/**
 * Created by yangle on 2017/10/9.
 */
@Component
public class CustAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private SnailUserDetailsService userService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        CustUserDetails userDetials = (CustUserDetails) userService.loadUserByUsername(username);
        CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails();
        String code=details.getCode();
        String kapacode=details.getKapacode();
        String img=details.getImg();
        if(img!=null&&!img.equals("")){
            //注册百度云 人脸识别 提供的信息
            String APP_ID = "11267053";
            String API_KEY = "qEGTBgkmA4KI93SxADwap50L";
            String SECRET_KEY = "ioGgwVGM8gfNvnZGdIyICtUQ5Br11W5P";
            AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            String userid=login(img,client);
            if(userid!=null){
                 userDetials = (CustUserDetails) userService.loadUserByUsername(userid);
                if(userDetials!=null){
                    password=userDetials.getPassword();
                }else{
                    throw new BadCredentialsException("当前用户不存在，或者未在人脸库中移除");
                }
            }else{
                throw new BadCredentialsException("人脸验证失败");
            }

        }else {

//            if (!kapacode.equals(code)) {
//                throw new BadCredentialsException("验证码不正确");
//            }
            if (userDetials == null) {
                throw new BadCredentialsException("没有这个用户.");
            }
            //加密过程在这里体现
            if (!password.equals(userDetials.getPassword())) {
                throw new BadCredentialsException("密码错误");
            }
        }
        Collection<? extends GrantedAuthority> authorities = userDetials.getAuthorities();
        return new UsernamePasswordAuthenticationToken(userDetials, password, authorities);
    }

    public boolean supports(Class<?> arg0) {
        return true;
    }
    public JsonRootBean verifyUser(AipFace client, String img) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "1");
        String image = img;
        String imageType = "BASE64";
        String groupIdList = "yang";
        // 人脸搜索
        JSONObject res = client.search(image, imageType,groupIdList,options);
        JsonRootBean jsonRootBean= JSON.parseObject(res.toString(),JsonRootBean.class);
        System.out.println(res.toString(2));
        return jsonRootBean;
    }
    public String login(String img, AipFace client) {
        // 图片名称

        try {
            JsonRootBean bean=verifyUser(client,img);
            if(bean!=null){
                Result result=  bean.getResult();
                if(result!=null){
                    if (result.getUser_list().get(0).getScore() > 90) {
                        // 匹配成功
                        return result.getUser_list().get(0).getUser_id();
                    } else {
                        //匹配失败
                        return null;

                    }
                }else{
                    //匹配失败
                   return null;
                }
            }

        } catch (Exception e) {
            // TODO 异常执行块！
            e.printStackTrace();
        }
        return null;
    }
    public boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}